package com.neusoft.init;

import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.InterruptableJob;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.UnableToInterruptJobException;
import org.quartz.impl.StdSchedulerFactory;

import com.neusoft.common.db.BaseDAO;
import com.neusoft.util.Configuration;
import com.neusoft.util.TimeToCaptureJob;

/**
 * 初始化定时任务服务
 * @author 郑兴龙 zheng-xl@neusoft.com
 * 
 *
 */
public class InitTaskService extends BaseDAO implements  InterruptableJob{

private static Logger logger = Logger.getLogger(InitTaskService.class.getClass());
	
	private static Scheduler _sched = null;
	private static String Driver = "oracle.jdbc.driver.OracleDriver";
	private static String Url = "jdbc:oracle:thin:@192.168.1.253:1521:orcl";
	private static String username = "zfbzyw";
	private static String password = "zfbzyw";
	private static URL appPath = Thread.currentThread().getContextClassLoader().getResource("");
	private static String propertyFile = "videoSuperintendConfig.properties";

	static {
		try {
			_sched = StdSchedulerFactory.getDefaultScheduler();
			init();
		} catch (SchedulerException e) {
			logger.error("静态块初始化定时任务异常！");
			e.printStackTrace();
		}
		
	}
	/**
	 * 任务ID
	 */
	public static final String JOB_DATA_STRING_TASK_ID = "JOB_DATA_STRING_TASK_ID";
	
	public Connection getConnection(){
		Connection connection = null;
		try {
			// 加载驱动
			Class.forName(Driver);
			connection = DriverManager.getConnection(Url, username, password);
		} catch (Exception e) {
			logger.error("获得数据库驱动异常！");
			e.printStackTrace();
		}
		return connection;
	}
	public static Configuration getProperties(String path){
		Configuration conf = new Configuration(path);
		return conf;
	}
	public static void init(){
		Thread thread  = new Thread(new Runnable() {
			public void run() {
				try {
					//开始任务
					String path = appPath.getPath()+propertyFile;
					initTask(getProperties(path));
				} catch (Exception e) {
					logger.error("初始化任务异常！");
					e.printStackTrace();
				}
			}
		});
		thread.start();
	}
	
	public static void initTask(Configuration conf) {
			try {
				//System.out.println("sched"+_sched.getGlobalJobListeners());
				boolean isTaskListChanged = false;
				String taskId = conf.getValue("taskId");
				
				_sched.interrupt(taskId,Scheduler.DEFAULT_GROUP);
				_sched.deleteJob(taskId,Scheduler.DEFAULT_GROUP);
				JobDetail job = new JobDetail(taskId,Scheduler.DEFAULT_GROUP, TimeToCaptureJob.class);
				job.getJobDataMap().put(JOB_DATA_STRING_TASK_ID, taskId);
				Trigger trigger = new CronTrigger(taskId,Scheduler.DEFAULT_GROUP,conf.getValue("timer"));
				Date ft = _sched.scheduleJob(job, trigger);
			    isTaskListChanged = true;
			    logger.info(job.getFullName() + " will [also] run at: " + ft);
			
			if (isTaskListChanged){
				_sched.start();
			}
			} catch (Exception e) {
				logger.error("定时器启动异常！");
				e.printStackTrace();
			}
		
	}

	/**
	* 移除任务
	* @param jobName任务名
	* @param jobGroupName任务组名
	* @param triggerGroupName触发器组名
	* @throws SchedulerException
	*/
	public static void removeJob(String jobName,String jobGroupName,String triggerGroupName) 
			throws SchedulerException{
	//  Scheduler sched = _sched.getScheduler();
	  String[] triggerNames = _sched.getTriggerNames(triggerGroupName);
	  if(triggerNames!=null){
		  for(int i=0;i<triggerNames.length;i++){
			  _sched.pauseTrigger(triggerNames[i],triggerGroupName);//停止触发器
			  _sched.unscheduleJob(triggerNames[i],triggerGroupName);//移除触发器 
		  }
	  }
	  _sched.deleteJob(jobName,jobGroupName);//删除任务
	}
	public void interrupt() throws UnableToInterruptJobException {
		// TODO Auto-generated method stub
		
	}
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		// TODO Auto-generated method stub
		
	}
	
	
	
}
